<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>The Ajax 02 Page</h1>
<fieldset>
    <legend>Ajax 表单请求</legend>
    <form enctype="application/x-www-form-urlencoded">
        <input type="text" name="name" id="nameId" onblur="doCheck()" onfocus="doClear()">
        <input type="button" onclick="doSave()" value="Save">
    </form>
    <span id="result"></span>
</fieldset>
</body>
<script type="text/javascript">
    function doCheck(){//在此函数中向服务端发起异步请求,检测name是否存在
        //1.创建XHR对象
        var xhr=new XMLHttpRequest();
        //2.设置状态监听
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4&&xhr.status==200){
                document.getElementById("result").innerHTML="<font color='red'>"+xhr.responseText+"</font>";
            }
        };
        //3.打开链接
        //var name=document.getElementById("nameId").value;
        var  name=document.forms[0].name.value;
        console.log("name",name);
        xhr.open("GET","/doCheck?name="+name,true);
        //4.发送请求
        xhr.send(null);//Get请求send方法传值
    }
    function doClear(){
            document.getElementById("result").innerHTML="";
    }

    function doSave(){
           //1.创建XHR对象
            var xhr=new XMLHttpRequest();
            //2.设置状态监听
            xhr.onreadystatechange=function(){
                 if(xhr.readyState==4&&xhr.status==200){
                      document.getElementById("result").innerHTML="<font color='red'>"+xhr.responseText+"</font>";
                 }
            };
            //3.打开链接
            //var name=document.getElementById("nameId").value;
            var  name=document.forms[0].name.value;
            xhr.open("POST","/doSave",true);
            //post请求要设置请求头(规定)
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            //4.发送请求
            xhr.send("name="+name);
            //Post请求send方法传值
    }
</script>
</html>